//
//  XGL_EditProfileViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/24.
//

import UIKit
import Alamofire
import TZImagePickerController

class XGL_EditProfileViewController: UIViewController,CustomNavgationBar{
    typealias UpdateCompleteBlock = ()->Void
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var headerImageView: UIImageView!
    var userNameText: UITextField!
    
    var headerImage: UIImage?
    var imageUrl: String?
    var id: String?
    var handler: UpdateCompleteBlock?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "Edit Profile")
        if XGL_userDataManager.share.userHeader.isEmpty == false{
            self.headerImageView.loadImageWithUrl(XGL_userDataManager.share.userHeader)
        }
        if XGL_userDataManager.share.userName.isEmpty == false{
            self.userNameText.text = XGL_userDataManager.share.userName
        }
    }

}

extension XGL_EditProfileViewController{
   
    @objc private func editHeaderAction(){
        let imagePick = TZImagePickerController(maxImagesCount: 1, delegate: self)
        imagePick?.allowCrop = false
        imagePick?.maxImagesCount = 1
        imagePick?.modalPresentationStyle = .fullScreen
        UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedString.Key.font: UIFont.pingfangSC_Semibold(fontSize: 15),NSAttributedString.Key.foregroundColor: UIColor.hexColor("#80FFE6")], for: UIControl.State.normal)
        self.present(imagePick!, animated: true, completion: nil)
    }
    
    @objc private func nextAction(){
        guard let name = self.userNameText.text,name.isEmpty == false else {
            MXProgressHUD.hudWithText("UserName cannot be empty")
            return
        }
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        if let image = self.headerImage {
            self.uploadHeaderRequest(image: image)
        }else{
            self.updateInforRequest()
        }
    }
}

extension XGL_EditProfileViewController{
    private func uploadHeaderRequest(image: UIImage){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(CustomRequestAPI(requestAPI: .Upload(image: image, file: "file"))) { result in
            switch result{
            case .success(let response):
                self.imageUrl = response.resultJson
                self.updateInforRequest()
                break
            default:
                break
            }
        }
    }
    
    private func updateInforRequest(){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(LoginRequestAPI(requestAPI: .CompleteInfor(infor: LoginData(treeId: self.id,nickname: self.userNameText.text!,header: self.imageUrl), param1: randomString(), param2: randomString()))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let block = self.handler {
                    block()
                }
                self.updateHeaderNicknameRequest()
                break
            default:
                break
            }
        }
    }
    
    private func updateHeaderNicknameRequest(){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .UpdateuserData(header: self.imageUrl, nickName: self.userNameText.text!))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                MXProgressHUD.hudWithText("Update successfully") {
                    self.navigationController?.popViewController()
                }
                break
            default:
                break
            }
        }
    }
}

extension XGL_EditProfileViewController:TZImagePickerControllerDelegate{

    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        if let selectImage = photos.first {
            self.headerImage = selectImage.compressed()
            self.headerImageView.image = selectImage
        }

    }

}
 
extension XGL_EditProfileViewController{
    private func createXglView(){
        self.headerImageView = UIImageView().then({ make in
            make.image = imageWithName("icon_header_default")
            make.layerCornerRadius = 50.0
            make.clipsToBounds = true
        })
        let editIconView = UIImageView().then { make in
            make.image = imageWithName("icon_header_edit")
        }
        let headerButton = UIButton().then { make in
            make.addTarget(self, action: #selector(self.editHeaderAction), for: .touchUpInside)
        }
        self.userNameText = UITextField().then({ make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Regular(fontSize: 16.0)
            make.attributedPlaceholder = "Ente here".attributesColor(UIColor.hexColor("#A2A2A2"),UIFont.pingfangSC_Regular(fontSize: 16.0))
        })
        let nameView = LoginUntil.creatLoginInputView(title: "UserName", inputText: self.userNameText)
        let nextButton = UIButton().then { make in
            make.setTitle("Submit", for: .normal)
            make.setTitleColor(UIColor.hexColor("#191A1D"), for: .normal)
            make.titleLabel?.font = UIFont.pingfangSC_Regular(fontSize: 18.0)
            make.backgroundColor = UIColor.hexColor("#80FFE6")
            make.layerCornerRadius = 24.0
            make.addTarget(self, action: #selector(self.nextAction), for: .touchUpInside)
        }
        self.view.addSubviews([headerImageView,editIconView,headerButton,nameView,nextButton])
        headerImageView.snp.makeConstraints { make in
            make.width.height.equalTo(100.0)
            make.top.equalTo(conversionWithScrennWidth(value: 147.0))
            make.centerX.equalToSuperview()
        }
        editIconView.snp.makeConstraints { make in
            make.right.bottom.equalTo(headerImageView)
            make.width.height.equalTo(24.0)
        }
        headerButton.snp.makeConstraints { make in
            make.edges.equalTo(headerImageView)
        }
        nameView.snp.makeConstraints { make in
            make.left.equalTo(15.0)
            make.centerX.equalToSuperview()
            make.top.equalTo(headerImageView.snp.bottom).offset(conversionWithScrennWidth(value: 60.0))
        }
        nextButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(conversionWithScrennWidth(value: 345.0))
            make.height.equalTo(48.0)
            make.bottom.equalTo(-BottomHeight-48.0)
        }
    }
    
}
